import { Button, Drawer, Form, Input, message } from 'antd'
import type { giftType } from '@/types'
import React, { useEffect, useState } from 'react'
import http from '@/utils/request'
import './index.scss'

const giftDrawer: React.FC<{ isOpen: boolean, gift?: giftType, onClose: (val: boolean) => void }> = ({ isOpen, gift, onClose }) => {
  const [form] = Form.useForm()
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    form.resetFields()
  }, [gift])

  const handleOk = () => {
    form?.validateFields()
      .then((values) => {
        setLoading(true)
        const url = gift?.id ? '/disp/biz/operation/update' : '/disp/biz/operation/insertBizType'
        http.post(url, {
          ...values,
          operationType: 'BizType',
          id: gift?.id
        }).then(() => {
          message.success(`${gift?.id ? '编辑' : '添加'}成功！`)
          onClose(true)
        }).catch(err => {
          message.error(err.msg || '操作失败')
        }).finally(() => {
          setLoading(false)
        })
      })
      .catch((errorInfo) => {
        console.log('校验失败:', errorInfo)
      })
  }
  const handleCancel = () => {
    onClose(false)
  }

  return (<Drawer
    title={`${gift?.id ? '编辑' : '添加'}业务类型`}
    closable={false}
    width={600}
    open={isOpen}>
    <div className="drawer-container flex-column">
      <Form
        form={form}
        initialValues={gift || {}}
        style={{ maxWidth: 600, marginTop: 20 }}
        layout="vertical">
        <Form.Item<giftType>
          label="名称"
          name="name"
          rules={[{ required: true, message: '业务类型名称为空!' }]}
        >
          <Input
            allowClear
            style={{ width: '100%' }}
          />
        </Form.Item>

        <Form.Item<giftType>
          label="备注"
          name="remark"
          rules={[{ required: false }]}
        >
          <Input
            allowClear
            style={{ width: '100%' }}
          />
        </Form.Item>
      </Form>
      <div className="flex1" />
      <div className="button-container flex-row">
        <div className="flex1" />
        <Button onClick={handleCancel} className="btn">取 消</Button>
        <Button onClick={handleOk} loading={loading} className="btn" type="primary">保 存</Button>
      </div>
    </div>
  </Drawer>)
}

export default giftDrawer
